﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Threading.Tasks;

namespace MeterControl.Services
{
    public class AsyncSocketTCPClient
    {
        #region 字段

        private Socket socket;
        private EndPoint localEP;
        private EndPoint remoteEP;
        private byte[] buffer = new byte[1024];//用于存放接收消息

        public event Action<byte[]> OnDataReceive;

        #endregion

        /// <summary>
        /// 建立TCP连接
        /// </summary> 
        public AsyncSocketTCPClient(IPAddress localIP, int localPort, IPAddress remoteIP, int remotePort)
        {
            //创建一个Socket实例
            socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            //绑定本地终结点
            localEP = new IPEndPoint(localIP, localPort);
            socket.Bind(localEP);
            //建立连接 
            remoteEP = new IPEndPoint(remoteIP, remotePort);
            socket.BeginConnect(remoteEP, new AsyncCallback(ConnectCallBack), this.socket);
        }

        /// <summary>
        /// 连接请求的回调
        /// </summary>
        /// <param name="ar"></param>
        private void ConnectCallBack(IAsyncResult ar)
        {
            Socket socketHandle = (Socket)ar.AsyncState;
            if (socketHandle.Connected)
            {
                socketHandle.EndConnect(ar);//结束挂起的异步连接请求
                socketHandle.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallBack), null);
            }
            else
            {
                //MessageBox.Show("连接失败");
            }
        }
        /// <summary>
        /// 接收数据的回调
        /// </summary>
        /// <param name="ar"></param>
        private void ReceiveCallBack(IAsyncResult ar)
        {
            if (socket == null) return;
            int length = socket.EndReceive(ar);//结束挂起的异步读取
            if (length > 0)
            {
                byte[] data = new byte[length];
                Array.Copy(buffer, 0, data, 0, length);
                OnDataReceive(data);

                socket.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallBack), null);
            }
        }
        /// <summary>
        /// 发送数据
        /// </summary>
        /// <param name="data"></param>
        public void SendData(byte[] data)
        {
            if (socket != null)
            {
                socket.Send(data);
            }
        }

        /// <summary>
        /// 关闭
        /// </summary>
        public void Close()
        {
            if (socket != null)
            {
                socket.Close();
            }
        }

    }
}
